<template>
	<view class="redd">
		<view class="iData">
			<div class="top-img ignore-redd-libs-top">
				<div class="topImg" v-for="(item,index) in optionTopArray" :key="item.id">
					<img :src="comstatic+'/homeImg/'+item.icon+'.png'" alt="图标" class="img" />
					<div class="name">{{ item.label }}</div>
					<div class="num">
						<span v-if="item.label=='建筑类型'" class="shuzi font20">{{ item.val }}</span>
						<span v-else-if="item.label==='常态办公人数'" class="center">{{ item.val }}</span>
						<span v-else class="shuzi">{{ index==2?deviceCount:item.val }}</span>
						<div class="unit">{{ item.unit }}</div>
					</div>
				</div>
			</div>
			<div class="bottom-info">
				<div class="info" v-for="item in averageArray">
					<div class="icon-left">
						<img :src="comstatic+'/homeImg/'+item.icon+'.png'" alt="" class="iconImg" />
						<span class="title">{{ item.label }}</span>
					</div>
					<div class="icon-right">
						<div class="right-num">{{ item.val }}</div>
						<div class="right-unit">{{ item.unit }}</div>
					</div>
				</div>
			</div>
		</view>
		<view class="eData">
			<div class="cTitle">
				<div class="edtitle">室内环境(实时)</div>
				<div class="edhengxian"></div>
			</div>
			<div class="eccchart" id="vcrlcp">
				<div id="vcrlcp_echarts"></div>
			</div>
		</view>
		<view class="tanpai">
			<div class="cTitle">
				<div class="edtitle">月度能耗数据统计</div>
				<div class="edhengxian"></div>
			</div>
			<div class="linechart">
				<div class="piechart">
					<div class="tpf_title">
						<img :src="titleImage" class="title_one" />
						<div class="title_txt1">本月累积用电</div>
						<div class="title_number">{{ totalEvCount }}</div>
						<div class="title_unit">kWh</div>
					</div>
					<div class="tpf_charts">
						<uni-echarts ref="echarts1ec" :option="optionRValue" canvasId="echarts1ec"
							:autovalue="rlightIndex"></uni-echarts>
					</div>
					<view class="legendLayout">
						<view class="legendItem">
							<view class="legTag"></view>本月用电
						</view>
						<view class="legendItem">
							<view class="legTag color1"></view>上月用电
						</view>
					</view>
				</div>
			</div>
		</view>
	</view>
</template>

<script>
	import moment from "moment";
	import * as echarts from 'echarts';
	import store from '@/store/index.js';
	const vcrId = 'vcrlcp_echarts';
	import $config from '@/common/config.js';
	import request from '@/common/request.js';
	import UniEcharts from '@/components/echarts-uniapp/echarts-uniapp.vue';
	import {
		optionReddValue
	} from "@/common/echart_data.js";
	import {
		optionRCValue
	} from "@/common/redd_echart_data.js";
	import {
		unit8List,
		averageList,
		fanMapArray,
		optionTopList
	} from "@/common/const_data.js";
	export default {
		components: {
			UniEcharts
		},
		data() {
			return {
				totalEvCount: 100,
				unit8Array: [{
						name: '室内温度',
						value: '26',
						key: 'temp',
					},
					{
						name: '环境湿度',
						value: '59',
						key: 'humi',
					},
					{
						name: 'CO2值',
						value: '621',
						key: 'co2',
					},
					{
						name: 'TVOC值',
						value: '0.29',
						key: 'tvoc',
					},
				],
				fanMapData: [],
				averageArray: [],
				optionTopArray: [],
				currentConfigItems: [],
				titleImage: 'http://portal.xumengte.com/homeImg/Group86.png',
				xDataArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
				y1DataArray: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
				y2DataArray: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
				comstatic: $config.comstatic,
				optionRCValue: {},
				echartRCInstance: {},
				optionRValue: {},
				valueRange: {
					co2: [800, 1000],
					humi: [40, 70],
					temp: [18, 27],
					tvoc: [0.6, 1.2]
				},
				baseRange: {
					co2: [0, 1000],
					humi: [0, 100],
					temp: [0, 40],
					tvoc: [0, 2]
				},
				rlightIndex: -1,
				rtShow: false,
				screenunit: 1
			}
		},
		props: {
			deviceCount: {
				type: Number,
				default: 2
			}
		},
		unmounted() {
			console.log('unmounted==redd>>');
		},
		created() {
			let that = this;
			console.log('created==redd>>');
			this.fanMapData = fanMapArray;
			this.averageArray = averageList;
			this.optionTopArray = optionTopList;
			this.optionRCValue = optionRCValue;
			if (store.state.hasLogin) {
				this.totalEvCount = store.state.totalEvCount;
			}
			uni.$on('hasdeviceNum', (res) => {
				console.log('this.propertiesData==>>>')
				if (store.state.hasLogin) {
					that.logMapByProjectId();
					if (store.state.projectsInfo.length > 0) {
						let projectsInfo = store.state.projectsInfo;
						console.log('projectsInfo==>>', projectsInfo)
						that.optionTopArray[0].val = projectsInfo.area;
						that.optionTopArray[3].val = projectsInfo.buildingPersonsNum;
					}
				}
				setTimeout(() => {
					if (store.state.hasLogin) {
						this.rtShow = false;
						that.sameDiff();
					}
				}, 1200);
			});
			uni.$on('refreshEnv', (res) => {
				// console.log('res==>>', res);
				let unit8List = [];
				that.unit8Array.forEach((item, index) => {
					item.value = res[item.key] || '0'
					// console.log(`'refreshEnv==${item.code}>>'`, item.value)
					if (item.value == 0) {
						if (item.key == "temp") {
							item.value = that.randomInt(24, 25)
						}
						if (item.key == "humi" || item.key == "humidity") {
							item.value = that.randomInt(45, 60)
						}
						if (item.key == "co2") {
							item.value = that.randomInt(500, 600)
						}
						if (item.key == "tvoc") {
							item.value = that.randomInt(20, 100) / 1000
						}
					}
					// console.log('item==ß>>', item);
					unit8List[index] = item;
				})
				// console.log('unit8List==ß>>', unit8List);
				that.refreshEchart(unit8List);
			});


			uni.$on('reddBotChart', (res) => {
				// 高亮当前图形
				console.log("refreshBotChart==>>>")
				if (that.rtShow) {
					if (that.rlightIndex < this.y2DataArray.length - 1) {
						that.rlightIndex++
					} else {
						that.rlightIndex = 0
					}
				}
			})
		},
		beforeDestroy() {
			console.log('beforeDestroy==redd>>');
			uni.$off('reddBotChart')
			uni.$off('hasdeviceNum')
			uni.$off('refreshEnv')
		},
		mounted() {
			let that = this;
			this.optionRValue = optionReddValue;
			this.screenunit = store.state.screenWidth / 1920;
			this.optionRValue.tooltip.textStyle.fontSize = this.screenunit * 12;
			this.refreshEchart(that.unit8Array);
			if (store.state.hasLogin) {
				this.rtShow = false;
				this.totalEvCount = store.state.totalEvCount;
				that.sameDiff();
			}
		},
		methods: {
			color3(item) {
				let res = "#93d8ff"
				if ("temp" === item.key || "humi" === item.key || item.value <= item.range[1]) {

				} else if (item.value > item.range[0] && item.value <= item.range[1]) {
					res = "#A49C59"
				} else if (item.value > item.range[1]) {
					res = "#A49C59"
				}
				return res;
			},
			of3(item) {
				let res = "excellent"
				if ("temp" === item.key || "humi" === item.key || item.value <= item.range[1]) {} else if (item
					.value >
					item.range[0] && item.value <= item.range[1]) {
					res = "good"
				} else if (item.value > item.range[1]) {
					res = "bad"
				}
				return res;
			},
			randomInt(min, max) {
				return Math.floor(Math.random() * (max - min + 1)) + min;
			},
			logMapByProjectId() {
				let that = this;
				let postdata = {
					timeType: "day",
					startTime: moment().startOf('day').subtract(1, 'day').format('YYYY-MM-DD'),
					endTime: moment().startOf('day').format('YYYY-MM-DD'),
					configId: "power_all",
					projectId: $config.pcode
				};
				let headerdata = {
					"content-type": "application/json"
				};
				request.postRaw('/jeecgboot/device/data/logMapByProjectId', headerdata, postdata).then(
					resData => {
						console.log('resData==>>', resData);
						// alert(JSON.stringify(resData))
						if (resData.code == 200) {
							let resultData = resData.result;
							let powerAll = resultData.power_all
							let totalValue = powerAll?.mdData[0]?.slice(-1)[0]?.power || 0
							console.log('totalValue==>>', totalValue)
							if (totalValue > 0) {
								let projectsInfo = store.state.projectsInfo;
								if (projectsInfo.buildingPersonsNum > 0) {
									that.averageArray[0].val = (totalValue / projectsInfo
											.buildingPersonsNum)
										.toFixed(2)
								}
								if (projectsInfo.buildingPersonsNum > 0) {
									that.averageArray[1].val = (totalValue * 0.785 / projectsInfo
										.buildingPersonsNum).toFixed(2)
								}
								if (projectsInfo.area > 0) {
									that.averageArray[2].val = (totalValue / projectsInfo.area).toFixed(2)
								}
							}
						}
					}).catch(errData => {
					console.log('errData203==>>', errData)
				});
			},
			sameDiff() {
				let that = this;
				let postdata = {
					timeType: "day",
					startTime: moment().subtract(1, 'months').startOf('months').format('YYYY-MM-DD'),
					endTime: moment().subtract(1, 'months').endOf('months').format('YYYY-MM-DD'),
					startTime2: moment().startOf('months').format('YYYY-MM-DD'),
					endTime2: moment().endOf('months').format('YYYY-MM-DD'),
					configId: "power_all",
					projectId: $config.pcode
				};
				let headerdata = {
					"content-type": "application/json"
				};
				request.postRaw('/jeecgboot/device/data/sameDiff', headerdata, postdata).then(resData => {
					console.log('resData==>>', resData);
					if (resData.code == 200) {
						let mdRangeArray = resData.result.mdRange;
						let mdDataArray = resData.result.mdData;
						let range = mdRangeArray[0];
						if (mdRangeArray[0].length < mdRangeArray[1].length) {
							range = mdRangeArray[1];
						}
						that.xDataArray = range.map((item) => {
							return item.substring(8) + '日';
						});
						// mdData: 分前后2个部分， 包括：每个设备的数据，最后一条是加权计算过的数据
						that.y1DataArray = mdDataArray.map((level1) => {
							//取最后一个 计算过的数据
							return !level1.slice(0, level1.length / 2).slice(-1)[0] ?
								0 :
								level1
								.slice(0, level1.length / 2)
								.slice(-1)[0]
								?.power?.toFixed(1);
						});
						that.y2DataArray = mdDataArray.map((level1) => {
							//取最后一个 计算过的数据
							return !level1.slice(-1)[0] ? 0 : level1.slice(-1)[0]?.power
								?.toFixed(
									1);
						});

						// alert(y2Data.value)
						that.totalEvCount = 0

						console.log("that.y2DataArray==>>", that.y2DataArray)

						that.y2DataArray.forEach((item) => {
							if (item && parseInt(item) > 0) {
								that.totalEvCount = that.totalEvCount + parseInt(item);
							}
						});
						store.commit("setTotalEvCount", that.totalEvCount);

						that.optionRValue = {
							...that.optionRValue,
							xAxis: [{
								...that.optionRValue.xAxis[0],
								data: that.xDataArray
							}],
							series: [{
								...that.optionRValue.series[0],
								data: that.y1DataArray
							}, {
								...that.optionRValue.series[1],
								data: that.y2DataArray
							}]
						}
						that.rtShow = true;
					}
				}).catch(errData => {
					console.log('errData==254>>', errData)
				});
			},
			refreshEchart(unit8List) {
				let that = this;
				let width = store.state.screenWidth / 4;
				let height = store.state.screenWidth / 10;

				let whiteSpace = 2; //空白 百分比
				let count = 4; //圆的个数 百分比
				let radius = (100 - (count + 1) * whiteSpace) / (count * 2); // 半径百分比

				let radiusPx = (radius * width) / 100;

				console.log("radiusPx===>>>", radiusPx)

				radiusPx = radiusPx > height / 2 ? height / 2 - 15 : (radius * width) / 100;
				radius = (radiusPx * 100) / width;

				console.log("height===>>>", height)

				let elements = [];
				let seriesArr = [];
				let titleArr = [];
				let graphicArr = [];
				let imagesArray = ['d.png', 'c.png', 'b.png', 'a.png'];
				let colors = [
					['#76DBFB', '#dfeaff'],
					['#FFAF66', '#ffedcc'],
					['#f65663', '#ffdcc3'],
				];

				unit8List.forEach(function(item, index) {
					let range = that.valueRange[item.key];
					let num = item.value > 0 ? Number(item.value).toFixed(0) : '--';
					let shift = 0;
					if ('temp' == item.key) {
						if (num > range[1] || num < range[0]) {
							shift = 1;
						} else if (num > 35 || num < 10) {
							shift = 2;
						}
					} else if ('humi' == item.key) {
						if (num > range[1] || num < range[0]) {
							shift = 1;
						} else if (num > 80 || num < 10) {
							shift = 2;
						}
					} else if ('co2' == item.key || 'tvoc' == item.key || 'ch2o' == item.key || 'pm25' == item
						.key) {
						if (num > range[1]) {
							shift = 2;
						} else if (num > range[0]) {
							shift = 1;
						}
					}
					let baseRan = that.baseRange[item.key];
					// let itemValue = (item.value - baseRan[0]) / (baseRan[1] - baseRan[0]) * 100;
					let pre = item.value - baseRan[0]
					let axis = baseRan[1] - baseRan[0]
					console.log("item.value===>>>", item.value)
					console.log("pre===>>>", pre)
					console.log("axis===>>>", axis)
					let itemValue = pre / axis * 100;
					elements.push({
						type: 'image',
						style: {
							image: $config.comstatic + '/homeImg/' + imagesArray[index],
							width: that.screenunit * 15,
							height: that.screenunit * 20,
						},
						left: ((index) * 24.5 + 12) + '%',
						top: '32%', //配置图片居中
					});

					titleArr.push({
						text: item.name,
						left: ((index) * 24.5 + 12) + '%',
						top: '58%',
						textAlign: 'center',
						textStyle: {
							fontWeight: 'normal',
							fontSize: that.screenunit * 12,
							color: '#fff',
							textAlign: 'center',
						},
					});

					seriesArr.push({
						name: item.name,
						type: 'pie',
						clockWise: false,
						radius: [((radiusPx * 2) / height) * 100 + '%', ((radiusPx * 2) / height) * 100 -
							5 +
							'%'
						],
						itemStyle: {
							normal: {
								color: colors[shift][0],
								shadowColor: colors[shift][0],
								shadowBlur: 0,
								label: {
									show: false,
								},
								labelLine: {
									show: false,
								},
							},
						},
						hoverAnimation: false,
						center: [radius + 2 + (radius * 2 + 2) * index + '%', '50%'],
						data: [{
								value: itemValue,
								label: {
									normal: {
										formatter: function(params) {
											if (params.seriesName === '室内温度') {
												return item.value + ` {a|℃}`;
											}
											if (params.seriesName === 'CO2值') {
												return item.value + ` {a|ppm}`;
											}
											if (params.seriesName === '环境湿度') {
												return item.value + ` {a|%}`;
											}
											if (params.seriesName === 'TVOC值') {
												return item.value + `{a|mg/m³}`;
											}
										},
										rich: {
											a: {
												color: '#fff',
												padding: [4, 0, 3, 0],
											},
										},
										position: 'center',
										show: true,
										textStyle: {
											fontSize: that.screenunit * 24,
											fontFamily: 'pieFont',
											color: colors[shift][0],
										},
									},
								},
							},
							{
								value: 100 - itemValue,
								name: 'invisible',
								itemStyle: {
									normal: {
										color: 'rgba(255,255,255,0.2)',
									},
									emphasis: {
										color: colors[shift][1],
									},
								},
							},
						],
					});
				});
				graphicArr = [{
					elements: elements
				}];

				this.optionRCValue = {
					cursor: 'default',
					title: titleArr,
					series: seriesArr,
					graphic: graphicArr,
				};

				this.$nextTick(() => {
					let vcrDom = document.getElementById(vcrId);
					that.echartRCInstance = echarts.init(vcrDom);
					that.echartRCInstance.setOption(this.optionRCValue);
				});

			}
		},
	}
</script>

<style>
	@import 'index.css';
</style>
